<template>
    <div class="modify-score">
        <!-- 查询学生 -->
        <header class="modify-header">
            <div class="left">
                <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
                <span>|</span>
                <span>{{ questionAction }}题目</span>
            </div>
            <div class="right">
                课程管理系统
            </div>
        </header>
        <main class="modify-main">
            <div class="form-container">
                <el-form ref="form" :model="form" :rules="rules" class="form-table">
                    <el-form-item label="题目类型" prop="questionType">
                        <el-select v-model="form.questionType" filterable placeholder="题目类型">
                            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="题目对应课程" prop="questionCourse">
                        <el-select v-model="form.questionCourse" filterable placeholder="题目对应课程">
                            <el-option v-for="item in options" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="题目内容" prop="questionContent">
                        <el-upload class="upload-demo" :action="uploadUrl" ref="upload01" :headers="headers"
                            :on-success="handleSuccess" :on-error="handleError" :file-list="fileList" :limit="1"
                            accept="*" list-type="text" :auto-upload="false">
                            <el-button size="small" type="primary" slot="trigger" icon="el-icon-folder-add">选择文件</el-button>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="参考答案" prop="answer">
                        <el-upload class="upload-demo" :action="uploadUrl" ref="upload02" :headers="headers"
                            :on-success="handleSuccessAnswer" :on-error="handleError" :file-list="fileList" :limit="1"
                            accept="*" list-type="text" :auto-upload="false">
                            <el-button size="small" type="primary" icon="el-icon-folder-add">选择文件</el-button>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="前言" prop="questionTopicIntroduction">
                        <el-input v-model="form.questionTopicIntroduction" type="textarea" :rows="8"
                            placeholder="请输入前言" />
                    </el-form-item>
                    <el-form-item class="btn-container"> </el-form-item>
                    <el-form-item>
                        <div class="btn-container">
                            <!-- <el-button @click="reset()">重置</el-button> -->
                            <el-button style="margin-left: 5px" size="small" type="success" @click="submitUpload"
                                icon="el-icon-upload">
                                确认上传文件
                            </el-button>
                            <el-button type="primary" @click="confirm()" icon="el-icon-check">确定题目</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
        </main>
    </div>
</template>

<script>
import { addQuestionAPI, editQuestionAPI,  } from "@/api/question";
import { getTokenLocalStorage } from "@/utils/utilLocalStorage";

export default {
    name: 'timeTable',
    data() {
        return {
            questionAction: '',//标题
            //修改时
            questionId: '',
            //文件上传路径
            uploadUrl: 'http://localhost:8081/file/upload',
            fileList: [], // 初始化文件列表
            headers: {
                // 假设您需要添加一个名为 'Authorization' 的请求头
                Authorization: ''
            },
            //提交表单
            form: {
                questionType: '',
                questionCourse: '',
                questionContent: '',
                questionTopicIntroduction: '',
                answer: ''
            },
            rules: {
                questionType: [
                    { required: true, message: '请选择题目类型', trigger: 'change' }
                ],
                questionCourse: [
                    { required: true, message: '请选择题目对应课程', trigger: 'change' }
                ],
                questionContent: [
                    { required: true, message: '请输入题目内容', trigger: 'blur' }
                ],
                questionTopicIntroduction: [
                    { required: true, message: '请输入前言', trigger: 'blur' }
                ],
                //答案选填
                // answer: [
                //     { required: true, message: '请输入参考答案', trigger: 'blur' }
                // ]
            },
            //题目类型选项
            typeOptions: [{
                value: '简答题',
                label: '简答题'
            }, {
                value: '设计题',
                label: '设计题'
            }, {
                value: '其他',
                label: '其他'
            }],
            //题目对应课程选项
            options: [{
                value: '计算机类',
                label: '计算机类'
            }, {
                value: '管理类',
                label: '管理类'
            }, {
                value: '理工类',
                label: '理工类'
            }, {
                value: '艺术类',
                label: '艺术类'
            }, {
                value: '其他',
                label: '其他'
            }],

        }
    },
    created() {

    },
    mounted() {
        this.getgetQuestions()
        this.headers.Authorization = getTokenLocalStorage()
    },
    methods: {
        //确认上传文件
        submitUpload() {
            this.$refs.upload01.submit();
            this.$refs.upload02.submit();
        },
        // 文件上传处理
        handleSuccess(response, file, fileList) {
            if (response.code === 200) {
                this.$message.success('上传题目内容文件成功');
                // 假设 response.data 是上传成功后的文件链接
                this.form.questionContent = response.data;
                console.log('题目内容文件上传成功，文件链接：', response.data);
            } else {
                this.$message.error(`文件上传失败，${response.message}`);
            }
        },
        handleSuccessAnswer(response, file, fileList) {
            if (response.code === 200) {
                this.$message.success('上传参考答案文件成功');
                // 假设 response.data 是上传成功后的文件链接
                this.form.answer = response.data;
                console.log('参考答案文件上传成功，文件链接：', response.data);
            } else {
                this.$message.error(`文件上传失败，${response.message}`);
            }
        },
        handleError(err, file, fileList) {
            this.$message.error(`文件上传失败，${err}`);
        },
        //编辑数据回显
        getgetQuestions() {
            // 获取问题ID
            const questionId = this.$route.query.questionId;
            // 检查问题ID是否有效
            if (questionId) {
                // 进入编辑模式
                this.form = this.$route.query.question;
                this.questionId = questionId;
                this.questionAction = '修改';
            } else {
                // 进入添加模式
                this.questionAction = '添加';
            }
        },
        //确认
        confirm() {
            console.log(this.form);
            // 向uploadUrl地址发送上传文件,
            // 然后得到form.questionContent和form.answer,
            // 最后携带form发送POST或PUT请求
            this.submitUpload()
            // 使用 Element UI 的表单验证方法进行非空校验
            console.log(this.$refs.form);
            this.$refs.form.validate((valid) => {
                if (!valid) {
                    this.$message.error('输入信息不能为空');
                    return false;
                }
                // 显示加载状态
                const loading = this.$loading({
                    lock: true,
                    text: '正在添加题目...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                // 准备要提交的数据
                // addQuestionAPI是批量上传题目接口，此处只添加一条
                var formData = [this.form];
                if (!this.questionId || this.questionId === undefined) {
                    // 调用 API 添加题目
                    addQuestionAPI(formData).then((res) => {
                        // 隐藏加载状态
                        loading.close();
                        if (res.code == 200) {
                            this.$message.success('添加题目成功！');
                            // 这里可以添加额外的成功处理逻辑，例如重置表单或跳转到其他页面
                        } else {
                            this.$message.error('添加题目失败：' + res.message);
                            // 这里可以添加额外的失败处理逻辑
                        }
                    }).catch((error) => {
                        // 隐藏加载状态
                        loading.close();
                        // 处理请求异常
                        this.$message.error('添加题目请求异常：' + error.message);
                    });
                } else {
                    //编辑
                    editQuestionAPI(this.questionId, this.form).then((res) => {
                        // 隐藏加载状态
                        loading.close();
                        if (res.code == 200) {
                            this.$message.success('修改题目成功！');
                            // 这里可以添加额外的成功处理逻辑，例如重置表单或跳转到其他页面
                        } else {
                            this.$message.error('修改题目失败：' + res.message);
                            // 这里可以添加额外的失败处理逻辑
                        }
                    }).catch((error) => {
                        // 隐藏加载状态
                        loading.close();
                        // 处理请求异常
                        this.$message.error('您没有修改题目信息，修改题目请求异常：');
                    });
                }

            });
        },

    }
}
</script>

<style lang="scss" scoped>
.modify-score {
    background-color: #f4f6f8;
    height: 150vh;

    .modify-header {
        display: flex;
        justify-content: space-between;
        padding: 0 20px;
        height: 64px;
        line-height: 64px;
        font-size: 16px;
        font-weight: bold;
        background-color: #fff;

        .left {
            span {
                margin-right: 4px;
            }

            .arrow {
                cursor: pointer;
            }
        }

        .right {
            text-align: right;
        }
    }




}

.form-container {
    margin-left: 20%;
    margin-right: 20%;
    // border-style: solid;
    border-style: groove;

    .btn-container {
        display: flex;
        justify-content: center;
    }

}

.form-table {
    margin: 5%;
}
</style>
